use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(OrderPayments::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(OrderPayments::Id)
                            .string()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(OrderPayments::OrderId).string().not_null())
                    .col(ColumnDef::new(OrderPayments::ChargeId).string().not_null())
                    .col(
                        ColumnDef::new(OrderPayments::Amount)
                            .decimal_len(8, 2)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(OrderPayments::HandlingFee)
                            .decimal_len(8, 2)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(OrderPayments::Paid)
                            .tiny_integer()
                            .not_null(),
                    )
                    .col(ColumnDef::new(OrderPayments::Reference).text())
                    .col(
                        ColumnDef::new(OrderPayments::CreatedAt)
                            .timestamp_with_time_zone()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(OrderPayments::UpdatedAt)
                            .timestamp_with_time_zone()
                            .default(Expr::current_timestamp()),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_order_payments_order_id")
                            .from(OrderPayments::Table, OrderPayments::OrderId)
                            .to(Orders::Table, Orders::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(OrderPayments::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum OrderPayments {
    Table,
    Id,
    OrderId,
    ChargeId,
    Amount,
    HandlingFee,
    Paid,
    Reference,
    CreatedAt,
    UpdatedAt,
}

#[derive(DeriveIden)]
enum Orders {
    Table,
    Id,
}
